package com.huijie.app.u.shiro;

import com.huijie.app.u.shiro.impl.FilteRulesProviderImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsets.shiro.util.ShiroUtils;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.Map;

/**
 * @ClassName ContextListener
 * @Description web上下文监听器
 * @Author zyc
 * @Date 2018/12/20 10:52
 * @Version 1.0
 */
@WebListener
public class ContextListener implements ServletContextListener {

    private static final Log log = LogFactory.getLog(ContextListener.class);


    /**
     * @param event
     * @return void
     * @description: 目前用来监听web容器初始化后，重载shiro规则
     * @author zyc
     * @date 2018/12/20 10:59
     */
    @Override
    public void contextInitialized(ServletContextEvent event) {
        log.debug("自定义监听器启动");
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
        Map<String, HandlerMapping> allRequestMappings = BeanFactoryUtils.beansOfTypeIncludingAncestors(webApplicationContext,
                HandlerMapping.class, true, false);
        allRequestMappings.entrySet().forEach(e->{
            //本项目只需要RequestMappingHandlerMapping中的URL映射
            HandlerMapping handlerMapping = e.getValue();
            if ("requestMappingHandlerMapping".equals(e.getKey()) && handlerMapping instanceof RequestMappingHandlerMapping) {
                FilteRulesProviderImpl.setHandlerMapping((RequestMappingHandlerMapping) handlerMapping);
                log.debug("重载shiroFilterRules:   "+e.getKey());
                ShiroUtils.reloadFilterRules();
            }
        });
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }
}